package com.xwj.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.meta.InsertOnly;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;


/**
 * Created by xuweijie on 2017/6/7.
 */
@Configuration
public class FileUploadCosConfig {
    @Value("${cos.appid}")
    private long appId;
    @Value("${cos.secretId}")
    private String secretId;
    @Value("${cos.secretKey}")
    private String secretKey;
    @Value("${cos.bucketName}")
    private String bucketName;
//    @Value("${cos.cosPath}")
//    private String cosPath;

    private COSClient cosClient;

    public COSClient FileUploadCos() {
        // 初始化秘钥信息
        Credentials cred = new Credentials(appId, secretId, secretKey);
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion("gz");
        // 初始化cosClient
        return new COSClient(clientConfig, cred);
    }

    /**
     * 上傳照片
     *
     * @param localpath:本地上傳文件的路徑
     * @return
     */
    public String uploadFile(String uploadpath, String localpath, String fileName) {
        cosClient = FileUploadCos();
//        String suffix=fileName.substring(0,fileName.lastIndexOf("."));
        uploadpath += fileName;
        UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, uploadpath, localpath);
        uploadFileRequest.setInsertOnly(InsertOnly.OVER_WRITE);//文件已存在則覆蓋原文件
//        return parseData(cosClient.uploadFile(uploadFileRequest));
        return cosClient.uploadFile(uploadFileRequest);
    }

    /**
     * @param data
     * @return 解析獲取CDN鏈接
     */
    public String parseData(String data) {
        JSONObject obj = JSON.parseObject(data);
        JSONObject object2 = (JSONObject) obj.get("data");
        return object2.getString("access_url");
    }

}
